package com.sdnu.service.utiils.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.sdnu.common.utils.MD5;
import com.sdnu.service.entity.ucenter.User;
import com.sdnu.service.entity.ucenter.excel.UserDemo;
import com.sdnu.service.service.UserService;
import org.springframework.beans.BeanUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @Author: Zhao YunLai
 * @Date: 2021/12/05/19:21
 * @Description:
 */
public class WebExcelListener implements ReadListener<UserDemo> {

    private UserService userService;
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<User> list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public WebExcelListener(){

    }
    public WebExcelListener(UserService userService){
        this.userService=userService;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param userDemo    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(UserDemo userDemo, AnalysisContext context) {

        if(userDemo!=null&&userDemo.getAccount()!=null){
            User user = new User();
            System.out.println(userDemo);
            BeanUtils.copyProperties(userDemo,user);
            String account = userDemo.getAccount();
            String password = account.substring(account.length() - 4);
            password= MD5.encrypt(password);
            user.setPassword(password);

            //这里根据用户姓名生成用户头像，并把头像上传
            //暂时使用本地路径作为中转，之后可以删除
            String filePath = "E:\\code_workspace00\\utils_parent\\static\\avatar";
            //生成图片保存到本地文件夹并且上传到阿里云oss中返回图片地址
            String avatarUrl = userService.createAndUploadUserAvatar(userDemo.getName(), filePath);
            //设置头像
            user.setAvatar(avatarUrl);

            Integer gender = userDemo.getSex().equals("男")?0:1;
            user.setGender(gender)
                    .setIntro("你好，我是"+userDemo.getName());
            list.add(user);
        }

        if(list.size()>=BATCH_COUNT){
            saveData();
            //清除list
            list= ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    private void saveData(){
        userService.saveBatch(list);
    }


    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        System.out.println("所有数据解析完成");
    }
}
